package com.auto.survey.permission

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class PermissionManager private constructor(private val activity: Activity){

    // 权限列表
    private val permissions = mutableListOf<String>()
    // 权限组列表
    private val permissionGroups = mutableListOf<PermissionGroup>()
    // 权限申请结果回调
    private var callback: PermissionCallback? = null
    // 被拒绝权限的处理回调
    private var deniedHandler: DeniedPermissionHandler? = null
    // 权限解释说明提供者
    private var explanationProvider: PermissionExplanationProvider? = null
    // 是否强制申请所有权限（不允许部分授权）
    private var forceAllPermissions = false
    // 权限请求码
    private var requestCode = DEFAULT_REQUEST_CODE

    // ActivityResultLauncher 用于处理权限请求结果
    private var permissionLauncher: ActivityResultLauncher<Array<String>>? = null

    init {
        // 初始化 ActivityResultLauncher
        if (activity is AppCompatActivity) {
            permissionLauncher = activity.registerForActivityResult(
                ActivityResultContracts.RequestMultiplePermissions()
            ) { permissionsMap ->
                processPermissionResult(permissionsMap)
            }
        }
    }

    // 构建器类
    class Builder(private val activity: Activity) {
        private val manager = PermissionManager(activity)

        /**
         * 添加单个权限
         */
        fun addPermission(permission: String): Builder {
            manager.permissions.add(permission)
            return this
        }

        /**
         * 添加多个权限
         */
        fun addPermissions(vararg permissions: String): Builder {
            manager.permissions.addAll(permissions)
            return this
        }

        /**
         * 添加权限组
         */
        fun addPermissionGroup(group: PermissionGroup): Builder {
            manager.permissionGroups.add(group)
            return this
        }

        /**
         * 设置权限申请结果回调
         */
        fun setCallback(callback: PermissionCallback): Builder {
            manager.callback = callback
            return this
        }

        /**
         * 设置被拒绝权限的处理回调
         */
        fun setDeniedHandler(handler: DeniedPermissionHandler): Builder {
            manager.deniedHandler = handler
            return this
        }

        /**
         * 设置权限解释说明提供者
         */
        fun setExplanationProvider(provider: PermissionExplanationProvider): Builder {
            manager.explanationProvider = provider
            return this
        }

        /**
         * 设置是否强制申请所有权限
         */
        fun setForceAllPermissions(force: Boolean): Builder {
            manager.forceAllPermissions = force
            return this
        }

        /**
         * 设置请求码
         */
        fun setRequestCode(requestCode: Int): Builder {
            manager.requestCode = requestCode
            return this
        }

        /**
         * 构建并启动权限申请
         */
        fun request() {
            manager.requestPermissions()
        }
    }

    // 启动权限申请
    private fun requestPermissions() {
        // 合并权限列表和权限组中的权限
        val allPermissions = mutableListOf<String>()
        allPermissions.addAll(permissions)

        // 添加权限组中的权限
        for (group in permissionGroups) {
            allPermissions.addAll(group.permissions)
        }

        // 过滤重复权限
        val uniquePermissions = ArrayList(allPermissions.distinct())

        // 检查哪些权限还未被授予
        val permissionsToRequest = getPermissionsToRequest(uniquePermissions)

        if (permissionsToRequest.isEmpty()) {
            // 所有权限都已授予
            callback?.onAllPermissionsGranted()
        } else {
            // 需要申请权限
            if (explanationProvider != null) {
                // 检查是否需要显示权限解释
                if (shouldShowExplanation(permissionsToRequest)) {
                    val explanation = explanationProvider!!.getExplanation(permissionsToRequest)
                    showExplanationDialog(explanation) {
                        executePermissionRequest(permissionsToRequest)
                    }
                    return
                }
            }

            // 直接申请权限
            executePermissionRequest(permissionsToRequest)
        }
    }

    // 执行权限申请
    private fun executePermissionRequest(permissions: List<String>) {
        if (permissionLauncher != null) {
            // 使用 ActivityResult API (AndroidX)
            permissionLauncher!!.launch(permissions.toTypedArray())
        } else {
            // 传统方式
            ActivityCompat.requestPermissions(
                activity,
                permissions.toTypedArray(),
                requestCode
            )
        }
    }

    // 处理权限申请结果
    private fun processPermissionResult(permissionsMap: Map<String, Boolean>) {
        val grantedPermissions = mutableListOf<String>()
        val deniedPermissions = mutableListOf<String>()
        val permanentlyDeniedPermissions = mutableListOf<String>()

        permissionsMap.forEach { (permission, isGranted) ->
            if (isGranted) {
                grantedPermissions.add(permission)
            } else {
                deniedPermissions.add(permission)
                if (!shouldShowRequestPermissionRationale(permission)) {
                    permanentlyDeniedPermissions.add(permission)
                }
            }
        }

        // 处理结果
        if (deniedPermissions.isEmpty()) {
            // 所有权限都已授予
            callback?.onAllPermissionsGranted()
        } else {
            // 有权限被拒绝
            val result = PermissionResult(
                grantedPermissions = grantedPermissions,
                deniedPermissions = deniedPermissions,
                permanentlyDeniedPermissions = permanentlyDeniedPermissions
            )

            if (forceAllPermissions && !result.isAllGranted) {
                // 强制要求所有权限，但未全部授予
                callback?.onSomePermissionsDenied(result)

                // 处理被拒绝的权限
                if (deniedHandler != null) {
                    deniedHandler!!.handleDeniedPermissions(result)
                }
            } else {
                // 部分权限被拒绝，但不强制要求全部授予
                callback?.onPermissionsGrantedPartially(result)
            }
        }
    }

    // 检查是否需要显示权限解释
    private fun shouldShowExplanation(permissions: List<String>): Boolean {
        for (permission in permissions) {
            if (shouldShowRequestPermissionRationale(permission)) {
                return true
            }
        }
        return false
    }

    // 检查是否需要显示权限申请解释
    private fun shouldShowRequestPermissionRationale(permission: String): Boolean {
        return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
    }

    // 获取需要申请的权限
    private fun getPermissionsToRequest(permissions: List<String>): List<String> {
        val result = mutableListOf<String>()

        for (permission in permissions) {
            if (!isPermissionGranted(permission)) {
                result.add(permission)
            }
        }

        return result
    }

    // 检查权限是否已授予
    private fun isPermissionGranted(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(
            activity,
            permission
        ) == PackageManager.PERMISSION_GRANTED
    }

    // 显示权限解释对话框
    private fun showExplanationDialog(explanation: String, onConfirm: () -> Unit) {
        // 这里实现自定义对话框，实际使用时可以替换为任何对话框实现
        // 例如使用 MaterialDialog 或原生 AlertDialog

        // 示例代码：

        AlertDialog.Builder(activity)
            .setTitle("权限申请说明")
            .setMessage(explanation)
            .setPositiveButton("确定") { dialog, _ ->
                dialog.dismiss()
                onConfirm()
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
                callback?.onPermissionRequestCancelled()
            }
            .show()

    }



    // 权限结果类
    data class PermissionResult(
        val grantedPermissions: List<String>,
        val deniedPermissions: List<String>,
        val permanentlyDeniedPermissions: List<String>
    ) {
        val isAllGranted: Boolean
            get() = deniedPermissions.isEmpty()

        val hasPermanentlyDenied: Boolean
            get() = permanentlyDeniedPermissions.isNotEmpty()
    }

    // 权限回调接口
    interface PermissionCallback {
        fun onAllPermissionsGranted()
        fun onPermissionsGrantedPartially(result: PermissionResult)
        fun onSomePermissionsDenied(result: PermissionResult)
        fun onPermissionRequestCancelled() {}
    }

    // 被拒绝权限的处理回调
    interface DeniedPermissionHandler {
        fun handleDeniedPermissions(result: PermissionResult)
    }

    // 权限解释说明提供者
    interface PermissionExplanationProvider {
        fun getExplanation(permissions: List<String>): String
    }

    // 权限组类
    class PermissionGroup(val name: String, val permissions: List<String>) {
        companion object {
            // 常见权限组定义
            val CAMERA = PermissionGroup(
                "相机",
                listOf(android.Manifest.permission.CAMERA)
            )

            val LOCATION = PermissionGroup(
                "位置",
                listOf(
                    android.Manifest.permission.ACCESS_FINE_LOCATION,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION
                )
            )

            @RequiresApi(Build.VERSION_CODES.S)
            val BLUETOOTH = PermissionGroup(
                "蓝牙",
                listOf(
                    android.Manifest.permission.BLUETOOTH,
                    android.Manifest.permission.BLUETOOTH_SCAN,
                    android.Manifest.permission.BLUETOOTH_CONNECT,
                    android.Manifest.permission.BLUETOOTH_ADMIN,
                    android.Manifest.permission.ACCESS_FINE_LOCATION,
                )
            )

            val STORAGE = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                PermissionGroup(
                    "存储",
                    listOf(
                        android.Manifest.permission.READ_MEDIA_IMAGES,
                        android.Manifest.permission.READ_MEDIA_VIDEO,
                        android.Manifest.permission.READ_MEDIA_AUDIO
                    )
                )
            } else {
                PermissionGroup(
                    "存储",
                    listOf(
                        android.Manifest.permission.READ_EXTERNAL_STORAGE,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                    )
                )
            }

            val CONTACTS = PermissionGroup(
                "联系人",
                listOf(android.Manifest.permission.READ_CONTACTS)
            )

            val MICROPHONE = PermissionGroup(
                "麦克风",
                listOf(android.Manifest.permission.RECORD_AUDIO)
            )

            val PHONE = PermissionGroup(
                "电话",
                listOf(
                    android.Manifest.permission.READ_PHONE_STATE,
                    android.Manifest.permission.CALL_PHONE
                )
            )

            val SMS = PermissionGroup(
                "短信",
                listOf(
                    android.Manifest.permission.READ_SMS,
                    android.Manifest.permission.SEND_SMS
                )
            )
        }
    }

    companion object {
        private const val DEFAULT_REQUEST_CODE = 1001

        /**
         * 创建权限管理器构建器
         */
        fun with(activity: Activity): Builder {
            return Builder(activity)
        }

        // 获取权限名称的辅助方法
        fun getPermissionName(permission: String): String {
            return when (permission) {
                android.Manifest.permission.CAMERA -> "相机"
                android.Manifest.permission.ACCESS_FINE_LOCATION -> "精确位置"
                android.Manifest.permission.READ_EXTERNAL_STORAGE -> "读取存储"
                // 其他权限...
                else -> permission
            }
        }

        // 打开应用设置页面
        fun openAppSettings(activity: Activity) {
            val intent = Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                Uri.fromParts("package", activity.packageName, null)
            )
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            activity.startActivity(intent)
        }
    }


}